package com.tangbuzhi.proxy;

import java.lang.reflect.*;
import java.lang.reflect.Proxy;

/**
 * 代理模式举例：例如程序猿小明因拖欠工资提起诉讼，于是找来律师代理打官司。
 */
public class ProxyCase {
    public interface ILawsuit {
        void submit();//提交申请

        void burden();//进行举证

        void defend();//开始辩护

        void finish();//诉讼完成
    }

    public static class Xiaoming implements ILawsuit {
        @Override
        public void submit() {
            System.out.println("老板拖欠工资，特此申请仲裁");
        }

        @Override
        public void burden() {
            System.out.println("劳动合同与过去一年的工资流水");
        }

        @Override
        public void defend() {
            System.out.println("证据确凿，无需辩护");
        }

        @Override
        public void finish() {
            System.out.println("诉讼成功，老板三日内结清工资");
        }
    }

    /*静态代理*/
    public static class Lawyer implements ILawsuit {
        private ILawsuit lawsuit;

        public Lawyer(ILawsuit lawsuit) {
            this.lawsuit = lawsuit;
        }

        @Override
        public void submit() {
            lawsuit.submit();
        }

        @Override
        public void burden() {
            lawsuit.burden();
        }

        @Override
        public void defend() {
            lawsuit.defend();
        }

        @Override
        public void finish() {
            lawsuit.finish();
        }
    }

    /*动态代理*/
    public static class DynamicProxy implements InvocationHandler {
        private Object obj;//代理对象的引用

        public DynamicProxy(Object obj) {
            this.obj = obj;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Object result = method.invoke(obj, args);
            return result;
        }
    }

    public static void main(String[] args) {
        ILawsuit xiaoming = new Xiaoming();
        ILawsuit lawyer = new Lawyer(xiaoming);
        lawyer.submit();//老板拖欠工资，特此申请仲裁
        lawyer.burden();//劳动合同与过去一年的工资流水
        lawyer.defend();//证据确凿，无需辩护
        lawyer.finish();//诉讼成功，老板三日内结清工资

        System.out.println("=======================================");
        ILawsuit xiaoMing = new Xiaoming();
        DynamicProxy dynamicProxy = new DynamicProxy(xiaoMing);
        ClassLoader classLoader = xiaoMing.getClass().getClassLoader();
        ILawsuit dynamicLawyer = (ILawsuit) Proxy.newProxyInstance(classLoader, new Class[]{ILawsuit.class}, dynamicProxy);
        dynamicLawyer.submit();//老板拖欠工资，特此申请仲裁
        dynamicLawyer.burden();//劳动合同与过去一年的工资流水
        dynamicLawyer.defend();//证据确凿，无需辩护
        dynamicLawyer.finish();//诉讼成功，老板三日内结清工资
    }

}
